package mark.tom.fiter;

import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import mark.tom.fiter.bean.AggregateBean;
import mark.tom.fiter.bean.ResolvedAggregateBean;

public class ResolverFactory extends ResponseResolver.Factory {

    @Override
    public ResponseResolver get() {
        return get(null);
    }

    public ResponseResolver get(IDataResolver dataResolver) {
        return new DefaultResolver(dataResolver);
    }

    private final static class DefaultResolver implements ResponseResolver {

        @Nullable
        private final IDataResolver dataResolver;

        DefaultResolver(@Nullable IDataResolver dataResolver) {
            this.dataResolver = dataResolver;
        }

        @NonNull
        @Override
        public AggregateBean resolve(@Nullable String res, @Nullable Class<?> clazz) {
            ResolvedAggregateBean aggregateBean = new ResolvedAggregateBean();
            try {
                if (null == res || res.trim().length() == 0) {
                    throw new NullPointerException("Response Is Null");
                }
                if (null != clazz && !TextUtils.isEmpty(res) && null != dataResolver) {
                    Object result;
                    // 判断字符串是以什么字符串开头->'{'表示是JSONObject,'[{'表示JSONArray
                    if (res.startsWith("{")) {
                        // 解析成对象
                        result = dataResolver.parseObject(res, clazz);
                    } else if (res.startsWith("[{") || (res.startsWith("[") && isSimpleClass(clazz))) {
                        // 解析成列表
                        result = dataResolver.parseArray(res, clazz);
                    } else {
                        result = res;
                    }
                    aggregateBean.setData(result);
                } else {
                    aggregateBean.setData(res);
                }
            } catch (Exception ex) {
                // Ignore
            }
            return aggregateBean;
        }

        private boolean isSimpleClass(Class<?> classBean) {
            return classBean == String.class || classBean == Long.class || classBean == Integer.class
                    || classBean == Float.class || classBean == Double.class;
        }
    }

}
